var red   = { x : 0.7347, y : 0.2653, z : 0 };
var green = { x : 0.2738,  y : 0.7174,  z : 0.0088 };
var blue  = { x : 0.1666, y : 0.0089, z : 0.8245 };
var rY = 0.2126;
var gY = 0.7152;
var bY = 0.0722;
var rgbMat = [ 2.2406, -1.3372, -0.4986,
    -0.9689,  1.8758,  0.0415,
    0.0557, -0.2040,  1.0570 ];
export function XYtoXYZ( x, y )
{
    let B = XYtoBarycentric(x,y,red,green,blue);

    let Y = Dot( B, { x : rY, y : gY, z : bY } );

    let dst = { r : Y * x / y, g : Y, b : Y * (1.0-x-y) / y };

    return dst;
}

 function XYtoBarycentric(x,y,a,b,c)
{
    var b1,b2,b3;

    b1  = (b.y-c.y)*(  x-c.x) + (c.x-b.x)*(  y-c.y);
    b1 /= (b.y-c.y)*(a.x-c.x) + (c.x-b.x)*(a.y-c.y);

    b2  = (c.y-a.y)*(  x-c.x) + (a.x-c.x)*(  y-c.y);
    b2 /= (b.y-c.y)*(a.x-c.x) + (c.x-b.x)*(a.y-c.y);

    b3  = 1 - b1 - b2;

    return { x : b1, y : b2, z : b3 };
}


function Dot(a,b)
{
    return a.x*b.x + a.y*b.y + a.z*b.z;
}

export  function XYZtoSRGB( src )
{
    let dst = { r : 0, g : 0, b : 0 };

    dst.r = rgbMat[0] * src.r + rgbMat[1] * src.g + rgbMat[2] * src.b;
    dst.g = rgbMat[3] * src.r + rgbMat[4] * src.g + rgbMat[5] * src.b;
    dst.b = rgbMat[6] * src.r + rgbMat[7] * src.g + rgbMat[8] * src.b;

    return dst;
}

export function SRGBtoRGB( src )
{
    let dst = { r : 0, g : 0, b : 0 };

    if( src.r > 0.00304 )
        dst.r = 1.055 * Math.pow(src.r, 1.0/2.4) - 0.055;
    else
        dst.r = 12.92*src.r;
    dst.r = clamp(dst.r,0.0,1.0);

    if( src.g > 0.00304 )
        dst.g = 1.055 * Math.pow(src.g, 1.0/2.4) - 0.055;
    else
        dst.g = 12.92*src.g;
    dst.g = clamp(dst.g,0.0,1.0);

    if( src.b > 0.00304 )
        dst.b = 1.055 * Math.pow(src.b, 1.0/2.4) - 0.055;
    else
        dst.b = 12.92*dst.b;
    dst.b = clamp(dst.b,0.0,1.0);

    return dst;
}

function clamp(x, min, max) {
    return Math.min(Math.max(x, min), max);
};
